package com.ouc.dataMange.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ouc.common.config.OUCAjaxResult;
import com.ouc.common.entity.FileTreeList;
import com.ouc.common.utils.file.FileUtils;
import com.ouc.dataMange.domain.Upload;
import com.ouc.dataMange.service.ISysDataSetService;
import com.ouc.dataMange.service.ISysMemoryDeviceService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ouc.common.annotation.Log;
import com.ouc.common.core.controller.BaseController;
import com.ouc.common.core.domain.AjaxResult;
import com.ouc.common.enums.BusinessType;
import com.ouc.dataMange.domain.SysDataElectronicChart;
import com.ouc.dataMange.service.ISysDataElectronicChartService;
import com.ouc.common.utils.poi.ExcelUtil;
import com.ouc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * electronicChartController
 *
 * @author ouc
 * @date 2025-07-25
 */
@RestController
@RequestMapping("/dataMange/electronicChart")
public class SysDataElectronicChartController extends BaseController {
  @Autowired
  private ISysDataElectronicChartService sysDataElectronicChartService;

  @Autowired
  private ISysMemoryDeviceService memoryDeviceService;

  @Autowired
  private ISysDataSetService dataSetService;

  /**
   * 查询electronicChart列表
   */
//    @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysDataElectronicChart sysDataElectronicChart) {
    startPage();
    List<SysDataElectronicChart> list = sysDataElectronicChartService.selectSysDataElectronicChartList(sysDataElectronicChart);
    return getDataTable(list);
  }

  /**
   * 导出electronicChart列表
   */
  @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:export')")
  @Log(title = "electronicChart", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysDataElectronicChart sysDataElectronicChart) {
    List<SysDataElectronicChart> list = sysDataElectronicChartService.selectSysDataElectronicChartList(sysDataElectronicChart);
    ExcelUtil<SysDataElectronicChart> util = new ExcelUtil<SysDataElectronicChart>(SysDataElectronicChart.class);
    util.exportExcel(response, list, "electronicChart数据");
  }

  /**
   * 获取electronicChart详细信息
   */
  @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:query')")
  @GetMapping(value = "/{dataId}")
  public AjaxResult getInfo(@PathVariable("dataId") Integer dataId) {
    return success(sysDataElectronicChartService.selectSysDataElectronicChartByDataId(dataId));
  }

  /**
   * 新增electronicChart
   */
  @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:add')")
  @Log(title = "electronicChart", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody SysDataElectronicChart sysDataElectronicChart) {
    return toAjax(sysDataElectronicChartService.insertSysDataElectronicChart(sysDataElectronicChart));
  }

  /**
   * 修改electronicChart
   */
  @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:edit')")
  @Log(title = "electronicChart", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody SysDataElectronicChart sysDataElectronicChart) {
    return toAjax(sysDataElectronicChartService.updateSysDataElectronicChart(sysDataElectronicChart));
  }

  /**
   * 删除electronicChart
   */
  @PreAuthorize("@ss.hasPermi('dataMange:electronicChart:remove')")
  @Log(title = "electronicChart", businessType = BusinessType.DELETE)
  @DeleteMapping("/{dataIds}")
  public AjaxResult remove(@PathVariable Integer[] dataIds) {
    return toAjax(sysDataElectronicChartService.deleteSysDataElectronicChartByDataIds(dataIds));
  }

  /**
   * 上传电子海图数据（zip格式）
   */
  @ResponseBody
  @RequestMapping("/uploadElectronicChartFile")
  public OUCAjaxResult uploadElectronicChartFile(MultipartFile file,
                                                 @RequestParam(value = "userName", required = false, defaultValue = "admin") String userName,
                                                 @RequestParam(value = "userId", required = false, defaultValue = "1") Integer userId,
                                                 @RequestParam(value = "dataSetId", required = false, defaultValue = "6") Integer dataSetId,
                                                 @RequestParam(value = "memoryId", required = false, defaultValue = "9") Integer memoryId) throws Exception {
    try {


      String[] fileSplit = file.getOriginalFilename().split("/");
      String fileDir = memoryDeviceService.selectSysMemoryDeviceById(memoryId).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(dataSetId).getDataSetDevice() + File.separator;
      File newFile = new File(fileDir);
      if (!newFile.exists()) {
        newFile.mkdirs();
      }
      String fileName = fileSplit[fileSplit.length - 1];
      file.transferTo(new File(fileDir, fileName));

      String fileFirstName = fileName.split(".zip")[0];
      String filePath = fileDir + fileFirstName;

      SysDataElectronicChart electronicChart = new SysDataElectronicChart();
      electronicChart.setDataSetId(dataSetId);
      electronicChart.setMemoryId(memoryId);
      electronicChart.setDataName(fileFirstName);
      electronicChart.setDataPath(File.separator + fileFirstName);
      electronicChart.setDataArea(fileFirstName);
      File srcfile = new File(fileDir + fileName);

      FileUtils.unZipDirFiles(srcfile, fileDir);
      File unzipFile = new File(filePath);
      electronicChart.setDataSize((int) (FileUtils.getFilesLength(unzipFile) / (1024 * 1024) + 1));

      sysDataElectronicChartService.insertSysDataElectronicChart(electronicChart);


      return OUCAjaxResult.ok("已上传电子海图数据");
    } catch (Exception e) {
      return OUCAjaxResult.error("未成功上传" + e);
    }

  }

  /**
   * 电子海图下载zip
   */
  @ResponseBody
  @RequestMapping("/download")
  public AjaxResult download(HttpServletResponse response, Integer dataId) {
    try {
      SysDataElectronicChart electronicChart = sysDataElectronicChartService.selectSysDataElectronicChartByDataId(dataId);
      String filePath = memoryDeviceService.selectSysMemoryDeviceById(electronicChart.getMemoryId()).getSysMemoryDevice() +
          dataSetService.selectSysDataSetById(electronicChart.getDataSetId()).getDataSetDevice() + electronicChart.getDataPath() + ".zip";
      if (!new File(filePath).exists()) {
        return AjaxResult.error("文件不存在，请重试");
      }
      File file = new File(filePath);
      response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//文件下载
//      response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName,"UTF-8"));//文件预览

      ServletOutputStream outputStream = response.getOutputStream();
      outputStream.write(FileUtils.getFileByteArray(file));//把文件的字节数写出去
      outputStream.flush();//刷新一下
      outputStream.close();//一定要关闭文件流


      return AjaxResult.success("文件下载成功");
    } catch (Exception e) {
      return AjaxResult.error(e.toString());
    }
  }

  /**
   * 电子海图数据统计
   */
  @ResponseBody
  @RequestMapping("/dataStatistics")
  public OUCAjaxResult dataStatistics() {
    Map<String, Integer> result = new HashMap<>();
    List<SysDataElectronicChart> list = sysDataElectronicChartService.selectSysDataElectronicChartList(null);
    result.put("数据个数", list.size());
    Integer dataSize = 0;
    Integer fileNum = 0;
    for (SysDataElectronicChart dataElectronicChart : list) {
      dataSize += dataElectronicChart.getDataSize();
      fileNum += FileUtils.getFileNum(dataElectronicChart.getDataPath());
    }
    result.put("数据所占空间", dataSize);
    result.put("文件数量", fileNum);
    return OUCAjaxResult.ok(result);
  }

  /**
   * 获取电子海图文件列表
   */
  @ResponseBody
  @RequestMapping("/getFileList")
  public OUCAjaxResult getFileList(@RequestParam(value = "dataId") Integer dataId) {
    try {
      SysDataElectronicChart electronicChart = sysDataElectronicChartService.selectSysDataElectronicChartByDataId(dataId);
      String filePath = memoryDeviceService.selectSysMemoryDeviceById(electronicChart.getMemoryId()).getSysMemoryDevice() +
          dataSetService.selectSysDataSetById(electronicChart.getDataSetId()).getDataSetDevice() + electronicChart.getDataPath();
      FileTreeList fileTreeList = FileUtils.getFileTreeList(filePath);
      return OUCAjaxResult.ok(fileTreeList);
    } catch (Exception e) {
      return OUCAjaxResult.error("文件不存在，请检查");
    }
  }
}
